const request = require('../../utils/request')
const config = require('../../config')
const eventBus = require('../../utils/eventBus')

Page({
  data: {
    isLoggedIn: false,
    userInfo: null,
    menuList: [
      {
        id: 'profile',
        icon: '/images/profile-icon.png',
        name: '个人资料',
        path: '/packageA/profile/index'
      },
      {
        id: 'booking',
        icon: '/images/booking-icon.png',
        name: '预约记录',
        path: '/packageB/booking-history/index'
      },
      {
        id: 'points',
        icon: '/images/points-icon.png',
        name: '我的积分',
        path: '/packageB/points/index'
      },
      {
        id: 'mall',
        icon: '/images/mall-icon.png',
        name: '积分商城',
        path: '/packageB/points-mall/index'
      },
      {
        id: 'settings',
        icon: '/images/settings-icon.png',
        name: '设置',
        path: '/packageA/settings/index'
      },
      {
        id: 'feedback',
        icon: '/images/feedback-icon.png',
        name: '意见反馈',
        path: '/packageA/feedback/index'
      },
      {
        title: '线下门店',
        icon: 'location',
        path: '/packageB/stores/index'
      }
    ]
  },

  onShow() {
    this.fetchUserInfo()
  },

  onLoad(options) {
    this.fetchUserInfo()
    
    // 使用eventBus监听用户信息更新事件
    eventBus.on('userInfoUpdated', () => {
      this.fetchUserInfo()
    })
    
    // 监听登录和登出事件
    eventBus.on('user-login', this.onUserLogin.bind(this))
    eventBus.on('user-logout', this.onUserLogout.bind(this))
  },

  onUnload() {
    // 页面卸载时移除事件监听
    eventBus.off('userInfoUpdated')
    eventBus.off('user-login')
    eventBus.off('user-logout')
  },

  async fetchUserInfo() {
    try {
      // 检查全局登录状态
      const app = getApp();
      if (!app.globalData.isLoggedIn) {
        this.setData({ userInfo: null });
        return;
      }
      
      // 获取当前用户ID
      const userId = app.globalData.userInfo?.id;
      if (!userId) {
        console.error('未找到用户ID');
        this.setData({ userInfo: null });
        return;
      }
      
      // 使用Promise.all但避免解构赋值
      const responses = await Promise.all([
        request({
          url: '/api/user/info',
          data: { userId }
        }),
        request({
          url: '/api/points/overview',
          data: { userId }
        })
      ])

      const userData = responses[0].data
      const pointsData = responses[1].data

      this.setData({
        userInfo: {
          avatar: userData.avatar ? config.development.baseURL + userData.avatar : '/images/default-avatar.png',
          name: userData.nickname || '用户' + userData.id,
          studentId: userData.student_id || '未设置',
          coursesCount: userData.courses_count || 0,
          points: pointsData.availablePoints || 0
        }
      })
    } catch (error) {
      console.error('获取用户信息失败:', error)
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      })
    }
  },

  onTapMenuItem(e) {
    const type = e.currentTarget.dataset.type
    const routes = {
      profile: '/packageA/profile/index',
      points: '/packageB/points/index',
      history: '/packageB/booking-history/index',
      settings: '/packageA/settings/index'
    }

    if (routes[type]) {
      wx.navigateTo({
        url: routes[type],
        fail: (err) => {
          console.error('页面跳转失败:', err);
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    }
  },

  // 处理TabBar点击事件
  onTabItemTap(item) {
    console.log('TabBar点击事件 - 我的页面:', item);
    const app = getApp();
    app.handleTabItemTap(this, item);
  },

  // 处理用户登录事件
  onUserLogin(userInfo) {
    this.fetchUserInfo();
  },

  // 处理用户登出事件
  onUserLogout() {
    this.setData({
      userInfo: null
    });
  },

  // 菜单项点击事件
  handleMenuClick(e) {
    const path = e.currentTarget.dataset.path;
    
    wx.navigateTo({
      url: path,
      fail: (err) => {
        console.error('页面跳转失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 跳转到登录页面
  navigateToLogin() {
    wx.switchTab({
      url: '/pages/index/index',
      success: () => {
        // 通知首页显示登录按钮
        setTimeout(() => {
          eventBus.emit('show-login-modal');
        }, 500);
      }
    });
  }
})